package com.powernode.controller;


import cn.hutool.crypto.digest.DigestUtil;
import com.powernode.common.Constants;
import com.powernode.domain.Result;
import com.powernode.domain.User;
import com.powernode.service.UserService;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    private UserService userService;

    @PostMapping("login.action")
    public Result login(String username, String password,String captcha, HttpSession session){
        String s = session.getAttribute(Constants.CAPTCHA_KEY).toString();
        //验证方式不区分大小写
        if (s.equalsIgnoreCase(captcha)){
            User user = userService.login(username, DigestUtils.md5DigestAsHex(password.getBytes()));
            if (null==user){
                return new Result(-1,"用户名或密码错误");
            }else {
                user.setPassword("");
                session.setAttribute(Constants.SESSION_USER_KEY,user);
                return new Result(200,"登陆成功");
            }
        }else {
            return new Result(-1,"验证码错误");
        }
    }
    @PostMapping("outLogin.action")
    public Result outLogin(HttpSession session){
        try {
            session.invalidate();
            return new Result(200,"退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1,"推出失败");
        }

    }
}

